import threading
import config as gv
from os import system, popen
from time import sleep

# status_code
# 状态码：-1 0 1 2
# -1:异常 0:未检测设备 1:检测到1台设备 2:检测到多设备

# status
# 状态 True False
# True:正在投屏 False:未投屏

status_dict = {'exception': -1, 'disconnect': 0, 'connected': 1, 'excessive': 2}
threadID_dict = {'MainThread': 1, 'StatusCheckThread': 2}
global_status_code = 0


class MainThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.status_code = 0
        self.status = False
        self.threadID = threadID_dict['MainThread']

    def run(self):
        while True:
            self.status_code = global_status_code
            if self.status_code == status_dict['disconnect']:
                if self.status:
                    self.status = False
                    print("[WARN]连接已断开")
                else:
                    print('[INFO]未检测到安卓设备')
            if self.status == False and self.status_code == status_dict['connected']:
                print("[INFO]即将开启投屏，以下为配置信息")
                ins = 'scrcpy --max-fps ' + str(gv.max_fps) + ' -b ' + str(gv.bit_rate) + 'M'
                if gv.record:
                    ins += ' -r file.mkv'
                if gv.always_on_top:
                    ins += ' --always-on-top'
                system(ins)
                gv.status = True
                print("[TIPS]稍后可继续投屏，退出请手动关闭本程序")
                system("pause")
            if self.status_code == status_dict['excessive']:
                self.status = False
                print("[WARN]多个设备已连接，调整为单个设备")
            sleep(5)


class StatusCheckThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.status = 0
        self.threadID = threadID_dict['StatusCheckThread']

    def run(self):
        while True:
            try:
                res = popen('adb devices').read().splitlines()  # 执行指令并处理结果
            except Exception:
                self.status = status_dict['exception']
            else:
                if res[0] == "List of devices attached" and len(res[1]):
                    if len(res[2]):
                        self.status = status_dict['excessive']
                    else:
                        self.status = status_dict['connected']
                else:
                    self.status = status_dict['disconnect']
            global global_status_code
            global_status_code = self.status
            sleep(4)


if __name__ == '__main__':
    print("[TIPS]注意开启USB调试")
    print("[TIPS]支持一台安卓设备的投屏")
    sleep(4)

    try:
        statusCheckThread = StatusCheckThread()
        mainThread = MainThread()

        statusCheckThread.start()
        mainThread.start()
        statusCheckThread.join()
        mainThread.join()
    except Exception:
        print("[WARN]程序出现异常")
        system('pause')
